import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import ReactQuill from 'react-quill';
import { Modal, Row, Col, Form, Card, Input, Select, Icon, Button, message, Switch } from "antd";
import Upload from "../../../components/Upload";
import 'react-quill/dist/quill.snow.css';

// const ReactQuill = dynamic({ loader: () => import('react-quill')});



const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;


const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = file => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png" || file.type === "application/msword" || file.type ==="application/vnd.openxmlformats-officedocument.wordprocessingml.document" || file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || file.type === "application/pdf";
  if (!isJPG) {
    message.error("仅允许上传JPG、PNG、Word、Excel、PDF文件!");
  }
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isLt2M) {
    message.error("图片文件不能大于2MB!");
  }
  return isJPG && isLt2M;
};



@connect(({ notice, global }) => ({
  baseUrl:global.baseUrl,
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  loading:notice.loading,
  detaildata:notice.detaildata,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class NoticeAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.noticeType = (this.props.match.path=="/notice/announce/detail/add" || this.props.match.path=="/notice/announce/:id/edit") ? "1" : (this.props.match.path=="/notice/notify/detail/add" || this.props.match.path=="/notice/notify/:id/edit") ? "2" : "0";
    this.detailId = this.props.match.params.id && this.props.match.params.id!='detail' ? this.props.match.params.id : 0;
    this.state={
      fileList: [],
      htmlText:'',
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });

    if (this.detailId!=0) {
        // 编辑时 读取详情
        dispatch({
          type: "notice/fetch_notice_info",
          payload: {
            noticeId: this.detailId
          }
        }).then(()=>{
          const {baseUrl} = this.props;
          this.setState({
            htmlText:this.props.detaildata.noticeCon,
            fileList:this.props.detaildata.noticeFilePath && this.props.detaildata.noticeFilePath.length>0 ? this.props.detaildata.noticeFilePath.map(item=>{
              item.url = baseUrl+ item.url;
              return item;
            }) : []
          })
        })
    }
  }

  componentWillUnmount(){
    const { dispatch } = this.props;
    dispatch({
      type: `notice/appendClearState`,
    })
  }




  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        const { htmlText } = this.state;
        const action = this.detailId!=0 ? 'edit' : 'add';
        const noticeId = this.detailId!=0 ? this.detailId : undefined;

        if(values.isTop){
          values.isTop = "01";
        }else{
          values.isTop = "02";
        }

        dispatch({
          type: `notice/${action}_notice`,
          payload: {
            ...values,
            noticeCon: htmlText,
            noticeType:this.noticeType,
            noticeId
          }
        }).then(() => {
            this.handleReset();
            message.success(this.detailId!=0 ? "信息已修改" : "信息已保存");
            this.goBack();
        });
      }
    });
  }

  goBack = () => {
    const { location, match } = this.props;
    const typeStr=this.noticeType=="1" ? "announce" : this.noticeType=="2" ? "notify" : "none";
    if(this.detailId===0){
      router.push({ pathname:`/notice/${typeStr}/list`});
    }else{
      router.push({ pathname:`/notice/${typeStr}/list`,  query: { ...location.query} });
    }
  }


  handleReset = () => {
    this.setState({
      fileList: this.props.detaildata.noticeFilePath,
      htmlText:this.props.detaildata.noticeCon ? this.props.detaildata.noticeCon : '',
    })
    this.props.form.resetFields();
  };




  // 多文件上传
  uploadFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    const filelist =
      e &&
      e.fileList.reduce((arr, current) => {
        if (
          current.response &&
          current.response.data &&
          current.response.data.token
        ) {
          return arr.concat(current.response.data.token);
        } else {
          if (current.status && current.status === "error") {
            return arr.concat([]);
          } else {
            return arr.concat(current.uid);
          }
        }
      }, []);
    return filelist;
  };

  handleUploadFiles = info => {
    let fileList = info.fileList;
    if(fileList.length > 5){
      message.error("最多只能上传5个文件")
      return false
    }

    if (info.file.status == "done") {
      //const filename_str = info.file.name.split(".");
      // this.props.form.setFieldsValue({
      //   project_name: filename_str[0]
      // });

      fileList = fileList.map(item => {
        if (item.response && item.response.error_no != "0") {
          item.status = "error";
        }
        return item;
      });
    }

    this.setState({ fileList });
  };

  handleRemoveUploadFiles = file => {};


  handleContentChange = (value)=> {
    this.setState({ htmlText: value })
  }

  modules =  {
    toolbar: [
      [{ 'header': [1, 2, 3, false] }],
      ['bold', 'italic', 'underline','strike', 'blockquote'],
      [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
      [{ 'color': [] }, { 'background': [] }],
      ['link'],
      ['clean']
      ],
  }

  formats= [
    'header',
    'bold', 'italic', 'underline', 'strike', 'blockquote',
    'list', 'bullet', 'indent',
    'color', 'background',
    'link',
    ]

  render() {
    const { loading, dictionaries, detaildata, selectSource } = this.props;
    const { fileList, htmlText } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    };
    const formItemLayoutOne = {
      labelCol: { span: 3 },
      wrapperCol: { span: 21 }
    };



    return (
       <Card
             bodyStyle={{padding:20}}
       >
            <Form layout="horizontal">
              <Row gutter={24}>
                <Col span={12}>
                  <FormItem {...formItemLayout} label="类型" colon={false}>
                    {getFieldDecorator("noticeClass", {
                      initialValue: this.detailId === 0 ? undefined : detaildata.noticeClass,
                      rules: [
                        { required: true, message: "请选择类型" },
                      ]
                    })(
                      <Select placeholder="请选择类型"    style={{ width: '100%' }}>
                        {dictionaries.noticeClass && dictionaries.noticeClass.map(item => (
                          <Option key={item.value} value={item.value}>{item.label}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem {...formItemLayout} label="是否置顶" colon={false}>
                    {getFieldDecorator("isTop", {
                      initialValue: this.detailId === 0 ? false : detaildata.isTop=="01" ? true : false,
                      valuePropName: 'checked',
                      rules: [
                        // { required: true, message: "请输入设备名称" },
                      ]
                    })(
                      <Switch  />
                    )}
                  </FormItem>
                </Col>

                <Col span={12}>
                  <FormItem {...formItemLayout} label="标题" colon={false}>
                    {getFieldDecorator("noticeTitle", {
                      initialValue: this.detailId === 0 ? undefined : detaildata.noticeTitle,
                      rules: [
                        { required: true, message: "请输入标题" },
                      ]
                    })(
                      <Input placeholder="请输入标题" />
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={24} >
                <Col span={3} >
                  <FormItem labelCol={{span: 24}} wrapperCol={{span: 0}}  colon={false}>
                  </FormItem>
                </Col>
                <Col span={21}>
                  {
                   <ReactQuill  value={htmlText}
                                modules={this.modules}
                                formats={this.formats}
                                style={{height:400}}
                                onChange={this.handleContentChange} />
                  }


                </Col>
              </Row>
              <Row gutter={24} style={{marginTop:70}}>
                {
                  this.noticeType=="2" &&
                  <Col span={12}>
                    <FormItem {...formItemLayout} label="接收单位" colon={false}>
                      {getFieldDecorator("maintenanceId", {
                        initialValue: this.detailId === 0 ? undefined : detaildata.maintenanceId,
                        rules: [
                          // { required: true, message: "请选择维保单位" },
                        ]
                      })(
                        <Select
                          placeholder={"请选择接收维保单位（不选默认全部接收）"}
                          mode="multiple"
                          allowClear={true}
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                          style={{ width: '100%' }}
                        >
                          {selectSource.maintenance && selectSource.maintenance.map(item => (
                            <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                }

                <Col span={24}>
                  <FormItem
                    {...formItemLayoutOne}
                    label="上传附件"
                    colon={false}
                  >
                    {getFieldDecorator("fileTokenArray", {
                      valuePropName: "file",
                      getValueFromEvent: this.uploadFile,
                    })(
                      <Upload
                        // defaultFileList={this.detailId === 0 ? null : detaildata.devDatum}
                        fileList={this.state.fileList}
                        onChange={this.handleUploadFiles}
                        onRemove={this.handleRemoveUploadFiles}
                      >
                        <Button>
                          <Icon type="upload" /> 上传
                        </Button>
                      </Upload>
                    )}
                  </FormItem>
                </Col>

              </Row>

              <Row gutter={24} >
                <Col span={24} style={{textAlign:'center',padding:30}}>
                    <Button
                      onClick={this.handleFormSubmit.bind(this)}
                      type="primary"
                      size="large"
                      style={{marginRight:15}}
                      loading={loading.model_submit}
                    >
                      提交
                    </Button>
                    <Button
                      onClick={this.handleReset.bind(this)}
                      type="default"
                      size="large"
                    >
                      重置
                    </Button>
                </Col>
              </Row>
            </Form>



       </Card>
    );
  }
}
